import {defineStore} from 'pinia'
import type {tokenType, rolesType, user, permissionsType} from '@/types/store/storeType'
import type {ITreeMenuItem} from '@/types/menu/menuType'
import {foramteRouterTree, getAllBreadcrumbList} from "@/layout/MenuUtils/generateRouter";
import {setLocal, clearLocal} from "@/utils/localStorage";
import {removeToken, setToken} from "@/utils/auth";
import dynamicRoute from '@/router/modules/dynamicRoute'
import loginReq from "@/service/loginReq";
import router from "@/router";

export const useCounterStore = defineStore('counter', () => {
        let user: globalThis.Ref<user> = ref({}) //登录用户信息
        let menuTree: globalThis.Ref<ITreeMenuItem[]> = ref([]) //过滤hidden后可显示在侧边栏菜单的路由表
        let menuList: globalThis.Ref<ITreeMenuItem[]> = ref([]) //可被生成路由结构的路由表
        let breadcrumbList: globalThis.Ref<Record<string, any>> = ref({}) //面包屑导航
        let token: globalThis.Ref<tokenType> = ref()
        let permissions: globalThis.Ref<permissionsType> = ref([]) //按钮权限
        let roles: globalThis.Ref<rolesType> = ref([]) //角色权限
        let navList: Ref<Array<{ icon?: string, title: string, path: string, close: boolean }>> = ref([{
            title: "首页",
            path: "/home",
            close: false
        }]) //标签菜单

        //登录获取token
        const login = (data: string) => {
            return new Promise(async (resolve, reject): Promise<void> => {
                // const loginRes: any = await baseRequest.post('/login', data)
                // if (loginRes.code == 200) {
                //     token.value = loginRes.data.token
                //     setToken(loginRes.data.token)
                //     resolve(true)
                // }
                const loginRes: any = await loginReq.get('/getBindWeb', {code: data})
                if (loginRes) {
                    token.value = loginRes.token
                    user.value = loginRes.user
                    setToken(loginRes.token)
                    setLocal('user', JSON.stringify(loginRes.user))
                    resolve(loginRes.user)
                }
            })
        }
        //登录获取用户信息
        const getUserInfo = () => {
            return new Promise(async (resolve, reject): Promise<void> => {
                // const userInfo: any = await baseRequest.post('/user')
                // if (userInfo.code == 200) {
                //     user.value = userInfo.data.user
                //     roles.value = userInfo.data.roles
                //     permissions.value = userInfo.data.permissions
                //     setLocal('user', JSON.stringify(userInfo.data.user))
                //     resolve(true)
                // }
                user.value = JSON.parse(getLocal('user') as any)
                roles.value = ["*:*:*"]
                permissions.value = ["*:*:*"]
                resolve(true)
            })
        }
        //处理后端返回来的路由表转换成可渲染主页菜单格式
        const getMenuTree = async (): Promise<void> => {
            // const menuTreeRes: any = await baseRequest.post('/menus')
            // if (menuTreeRes.code == 200) {
            //     menuList.value = menuTreeRes.data
            //     breadcrumbList.value = getAllBreadcrumbList(menuTreeRes.data)
            //     menuTree.value = foramteRouterTree(menuTreeRes.data)
            // }
            menuList.value = dynamicRoute as any
            breadcrumbList.value = getAllBreadcrumbList(dynamicRoute)
            menuTree.value = foramteRouterTree(dynamicRoute as any)
        }

        const addTabs = (tabItem: any, route: Record<string, any>) => {
            if (tabItem.meta.tagHidden) {
                navList.value = []
                return
            }
            if (navList.value.every(item => item.path !== tabItem.path)) {
                if (navList.value.some(v => v.path == '/home') || route.path == '/home') {
                    if (route.path == '/home') {
                        navList.value.push({
                            title: "首页",
                            path: "/home",
                            close: false
                        });
                    } else {
                        const tabPath = tabItem.path.includes("?") ? tabItem.path.substring(0, tabItem.path.indexOf("?")) : false
                        const navPathList = navList.value.filter(v => v.path.includes("?"))
                        const navPath = navPathList.some(item => item.path.substring(0, item.path.indexOf("?")) == tabPath)
                        if (navPath) {
                            const filterNavPathList = navList.value.filter(v => v.path.substring(0, v.path.indexOf("?")) !== tabPath)
                            navList.value = [...filterNavPathList, tabItem]
                        } else {
                            navList.value.push(tabItem);
                        }
                    }

                } else {
                    navList.value = [{
                        title: "首页",
                        path: "/home",
                        close: false
                    }, tabItem]
                }
            }
        };

        const removeTabs = (tabPath: string, isCurrent = true) => {
            if (isCurrent) {
                navList.value.forEach((item, index) => {
                    if (item.path !== tabPath) return;
                    const nextTab = navList.value[index + 1] || navList.value[index - 1];
                    if (!nextTab) return;
                    router.push(nextTab.path);
                });
            }
            // set tabs
            navList.value = navList.value.filter(item => item.path !== tabPath);
        };


        const closeMultipleTab = (tabsMenuValue: string) => {
            navList.value = navList.value.filter(item => {
                return item.path === tabsMenuValue || !item.close;
            });
        };

        const setTabs = (tabsMenuList: any) => {
            navList.value = tabsMenuList;
        };


        const setTabsTitle = (title: string) => {
            navList.value.forEach(item => {
                if (item.path == location.hash.substring(1)) item.title = title;
            });
        }

        const logOut = () => {
            return new Promise(resolve => {
                roles.value = []
                menuTree.value = []
                menuList.value = []
                permissions.value = []
                user.value = {}
                token.value = ''
                removeToken()
                clearLocal()
                setTabs([])
                resolve(true)
            })
        }
        return {
            user,
            navList,
            menuList,
            menuTree,
            breadcrumbList,
            token,
            permissions,
            roles,
            login,
            getUserInfo,
            getMenuTree,
            addTabs,
            setTabs,
            removeTabs,
            closeMultipleTab,
            setTabsTitle,
            logOut
        }
    },
    {
        persist: {
            key: 'navList',
            paths: ["navList"]
        },
    }
)
